package org.credo.thread.BlockingQueue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class BigTest {

	public static void main(String[] args) {
		//创建一个容量为1的BlockingQueue
		BlockingQueue<String> bq=new ArrayBlockingQueue<String>(1);
		//启动三个生产者线程
		new Producer(bq).start();
		new Producer(bq).start();
		new Producer(bq).start();
		//启动一个消费者线程
		new Consumer(bq).start();
	}
}
//内部类生产者
class Producer extends Thread{
	private BlockingQueue<String> bq;
	public Producer(BlockingQueue<String> bq){
		this.bq=bq;
	}
	public void run(){
		String[] strArr=new String[]{"Java","C++","C#"};
		for(int i=0;i<9999;i++){
			System.out.println(getName()+"生产");
			try {
				Thread.sleep(200);
				//尝试放入元素,如果队列已经满了,则线程堵塞
				bq.put(strArr[i%3]);
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println(getName()+"生产完成:"+bq);
		}
	}
}
//内部类消费者
class Consumer extends Thread{
	private BlockingQueue<String> bq;
	public Consumer(BlockingQueue<String> bq){
		this.bq=bq;
	}
	public void run(){
		while(true){
			System.out.println(getName()+"消费!");
			try {
				Thread.sleep(200);
				bq.take();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(getName()+"消费完成:"+bq);
		}
	}
}

